// 物料组库
import React, {Component} from 'react';
import {connect} from 'react-redux';
import actions_material from '../../store/actions/materialGroup';
import action_code from '../../store/actions/codeLibrary';
import {Tree} from 'antd';
import '../materialGroup/MaterialGroup.scss';
import './CodeContentLeft.scss';

const {TreeNode} = Tree;

class CodeContentLeft extends Component {

  // 点击选择
  onSelect = async (selectedKeys, info) => {
    console.log(selectedKeys, info);
    await this.props.IS_SELECTED(info.selected);
    await this.props.CURRENT_PAGE(1);
    if (info.selected === true) {
      const cate_code = selectedKeys.toString().split(',')[1];
      await this.props.CATE_CODE(cate_code);
      await this.props.GET_CODELIBRARY_INFO(cate_code, 1, 10);
    }
  };

  // 自己定义的渲染tree函数
  myRender = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={`(${item.cate_code}) ` + item.cate_title} key={[item.id, item.cate_code]}>
            {this.myRender(item.children)}
          </TreeNode>
        );
      } else {
        return (<TreeNode title={`(${item.cate_code})` + item.cate_title} key={[item.id, item.cate_code]} isLeaf/>);
      }
    });
  };

  componentDidMount() {
    // 获取数据 初始化调用 actions中的函数
    this.props.INIT_DATA();
  }

  componentWillUnmount() {
    this.props.IS_SELECTED('');
  }

  render() {
    if (this.props.data) {
      const {data} = this.props;
      return (
        data && <div className='materialBox'>
          <div className='materialBoxk'>
            <div className='treeBox'>
              <Tree
                accordion
                multiple={false}
                showLine
                blockNode
                onSelect={this.onSelect}
              >
                {this.myRender(data)}
              </Tree>
            </div>
          </div>
        </div>
      );
    }
  }
}

const mapStateToProps = state => {
  return {
    data: state.materialGroup.data,
    selectKey: state.materialGroup.selectKey
  };
};

export default connect(mapStateToProps, {...actions_material, ...action_code})(CodeContentLeft);
